/*
 * Copyright (C) 2017 Baidu, Inc. All Rights Reserved.
 */
package com.ibiz.znjd.baidu.face.manager;

import com.ibiz.znjd.baidu.face.model.AccessToken;
import com.ibiz.znjd.baidu.face.utils.HttpUtil;
import com.ibiz.znjd.baidu.face.utils.OnResultListener;


public class APIService {

    /**
     * ACCESS_TOKEN URL
     */
    private static final String ACCESS_TOEKN_URL = "https://aip.baidubce.com/oauth/2.0/token?";

    private String accessToken;

    private APIService() {

    }

    private static volatile APIService instance;

    public static APIService getInstance() {
        if (instance == null) {
            synchronized (APIService.class) {
                if (instance == null) {
                    instance = new APIService();
                }
            }
        }
        return instance;
    }

    // 初始化OKHttp
    public void init() {
        HttpUtil.getInstance().init();
    }

    /**
     * 设置accessToken 如何获取 accessToken 详情见:
     *
     * @param accessToken accessToken
     */
    public void setAccessToken(String accessToken) {
        this.accessToken = accessToken;
    }

    public String getAccessToken() {
        return accessToken;
    }

    /**
     * 明文ak/sk获取token
     *
     * @param listener 回调监听
     * @param ak       access key
     * @param sk       secret key
     */
    public void initAccessTokenWithAkSk(final OnResultListener<AccessToken> listener, String ak,
                                        String sk) {
        StringBuilder sb = new StringBuilder();
        sb.append("client_id=").append(ak);
        sb.append("&client_secret=").append(sk);
        sb.append("&grant_type=client_credentials");
        HttpUtil.getInstance().getAccessToken(listener, ACCESS_TOEKN_URL, sb.toString());
    }
}
